<template>
    <han-status-bar />
    <view class="region-picker">
        <!-- 头部导航 -->
        <view class="picker-header">
            <view class="nav-back" @click="handleBack">
                <han-icon name="return" size="38" />
            </view>
            <text class="title">{{ headerTitle }}</text>
        </view>

        <scroll-view class="picker-content" scroll-y>
            <!-- 省份列表 -->
            <template v-if="currentLevel === 'province'">
                <!-- 暂时不选 -->
                <view class="not-choose" @click="handleSkip">
                    <text class="text">暂时不选择</text>
                </view>

                <!-- 当前位置 -->
                <view class="current-position">
                    <view class="title">
                        <han-icon name="location" size="24" />
                        <text class="text">当前位置</text>
                    </view>
                    <text class="position">{{
                        currentLocation || '定位中...'
                    }}</text>
                </view>

                <!-- 省份列表 -->
                <view class="orther-position">
                    <text class="title">其他地区</text>
                    <view class="position-list">
                        <view
                            v-for="(group, index) in provinceGroupList"
                            :key="index"
                        >
                            <view class="group-letter">{{ group.letter }}</view>
                            <view
                                v-for="province in group.list"
                                :key="province.code"
                                class="position-item"
                                @click="selectProvince(province)"
                            >
                                <text>{{ province.province }}</text>
                                <han-icon name="advance" size="24" />
                            </view>
                        </view>
                    </view>
                </view>
            </template>

            <!-- 城市列表 -->
            <template v-if="currentLevel === 'city'">
                <view class="position-list">
                    <view
                        v-for="city in currentCityList"
                        :key="city.code"
                        class="position-item"
                        @click="selectCity(city)"
                    >
                        <text>{{ city.city }}</text>
                        <han-icon
                            name="advance"
                            size="24"
                            v-if="city.areas?.length"
                        />
                    </view>
                </view>
            </template>

            <!-- 区县列表 -->
            <template v-if="currentLevel === 'area'">
                <view class="position-list">
                    <view
                        v-for="area in currentAreaList"
                        :key="area.code"
                        class="position-item"
                        @click="selectArea(area)"
                    >
                        <text>{{ area.area }}</text>
                    </view>
                </view>
            </template>
        </scroll-view>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import pinyin from 'pinyin';
import regionData from '@/data/ChinaCitys.json';

// 当前定位
const currentLocation = ref('');
// 当前层级
const currentLevel = ref('province');
// 选中的省份
const selectedProvince = ref(null);
// 选中的城市
const selectedCity = ref(null);

// 头部标题
const headerTitle = computed(() => {
    switch (currentLevel.value) {
        case 'province':
            return '地区选择';
        case 'city':
            return selectedProvince.value?.province || '选择城市';
        case 'area':
            return selectedCity.value?.city || '选择区县';
        default:
            return '地区选择';
    }
});

// 当前城市列表
const currentCityList = computed(() => {
    return selectedProvince.value?.citys || [];
});

// 当前区县列表
const currentAreaList = computed(() => {
    return selectedCity.value?.areas || [];
});

// 获取拼音首字母
const getFirstLetter = (name) => {
    const result = pinyin(name, {
        style: pinyin.STYLE_FIRST_LETTER
    });
    return result[0]?.[0]?.toUpperCase() || '#';
};

// 省份分组数据
const provinceGroupList = computed(() => {
    const groups = {};

    regionData.forEach((province) => {
        const letter = getFirstLetter(province.province);
        if (!groups[letter]) groups[letter] = [];
        groups[letter].push(province);
    });

    // 转换为数组并按字母排序
    return Object.keys(groups)
        .sort()
        .map((letter) => ({
            letter,
            list: groups[letter].sort((a, b) =>
                a.province.localeCompare(b.province)
            )
        }));
});

// 选择省份
const selectProvince = (province) => {
    selectedProvince.value = province;

    // 如果只有一个城市，直接选择该城市
    if (province.citys.length === 1) {
        selectCity(province.citys[0]);
    } else {
        currentLevel.value = 'city';
    }
};

// 选择城市
const selectCity = (city) => {
    selectedCity.value = city;

    // 如果有区县，进入区县选择
    if (city.areas?.length > 0) {
        currentLevel.value = 'area';
    } else {
        // 没有区县，直接完成选择
        completeSelection();
    }
};

// 选择区县
const selectArea = (area) => {
    completeSelection(area);
};

// 完成地区选择
const completeSelection = (area = null) => {
    const selectedRegion = {
        province: selectedProvince.value,
        city: selectedCity.value,
        area: area
    };

    console.log(selectedRegion);

    // 通过事件总线传递选择结果
    uni.$emit('region-selected', selectedRegion);

    // 返回上一页
    uni.navigateBack();
};

// 暂时不选择
const handleSkip = () => {
    uni.$emit('region-selected', null);
    uni.navigateBack();
};

// 返回操作
const handleBack = () => {
    if (currentLevel.value === 'province') {
        uni.navigateBack();
    } else if (currentLevel.value === 'city') {
        currentLevel.value = 'province';
    } else if (currentLevel.value === 'area') {
        currentLevel.value = 'city';
    }
};
</script>

<style lang="scss">
.region-picker {
    height: 100vh;
    display: flex;
    flex-direction: column;

    .picker-header {
        display: flex;
        align-items: center;
        padding: 20rpx;
        border-bottom: 1rpx solid $han-global-border-color;
        position: relative;

        .nav-back {
            position: absolute;
            z-index: 10;
        }

        .title {
            font-size: $han-font-size-base;
            font-weight: bold;
            flex: 1;
            text-align: center;
        }
    }

    .picker-content {
        flex: 1;
        padding: 0 20rpx;
        overflow: hidden;
        height: 100%;

        .not-choose {
            display: flex;
            align-items: center;
            width: 100%;
            height: 100rpx;
            border-bottom: 1rpx solid $han-global-border-color;

            .text {
                font-size: $han-font-size-base;
            }
        }

        .current-position {
            width: 100%;
            border-bottom: 1rpx solid $han-global-border-color;
            padding: 20rpx 0;

            .title {
                display: flex;
                align-items: center;
                margin-bottom: 10rpx;
            }

            .position {
                font-size: $han-font-size-base;
                color: $han-primary-color;
            }
        }

        .orther-position {
            .title {
                display: flex;
                align-items: center;
                font-size: $han-font-size-sm;
                font-weight: bold;
                padding: 20rpx 0;
            }

            .group-letter {
                padding-top: 20rpx;
                font-size: $han-font-size-sm;
                color: $han-global-secondary-font-color;
            }
        }

        .position-list {
            .position-item {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding: 20rpx 0;

                &:last-child {
                    border-bottom: 1rpx solid $han-global-border-color;
                }

                .text {
                    font-size: $han-font-size-base;
                }
            }
        }
    }
}
</style>
